# -*- coding:utf-8 -*-
__author__ = 'xigu007'
from kivy.metrics import dp, sp
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import StringProperty,ListProperty
from kivy.uix.textinput import TextInput
from kivy.lang import Builder
from recycleview.staggered_layout import StaggeredViewMixin
from composite_widget.base import RelativeComposite,Division
from composite_widget.content import LabelContent, ImageContent, ShapeContent
from composite_widget.group import ShapeBackground
from composite_widget.context import WidgetContainer
from random import randint, sample
import os
Builder.load_string('''
<ChatLeftPad>
    wrap_content_height: True
    orientation: 'vertical'
    Division:
        absolute_height: dp(12)
    Division:
        Division:
            absolute_width: dp(68)
            ImageContent:
                size_hint: 0.75, None
                source:  root.user_pic
        Division:
            orientation: 'vertical'
            Division:
                contents_typesetting: 'anchor'
                absolute_height: dp(22)
                LabelContent:
                    color: 0.6,0.6,0.6,1
                    text: root.user_name
                    font_size: sp(13)
                    anchor: 'left'
                    margin: 10,8,0,0
            Division:
                contents_typesetting: 'anchor'
                BorderImageBackground:
                    id: content_container
                    image_source: './res/a84.9.png'
                    border: 18,10, 36, 8
                    anchor: 'left'
    Division:
        absolute_height: dp(12)
<ChatRightPad>
    wrap_content_height: True
    orientation: 'vertical'
    Division:
        absolute_height: dp(12)
    Division:
        Division:
            orientation: 'vertical'
            Division:
                absolute_height: dp(22)
            Division:
                contents_typesetting: 'anchor'
                BorderImageBackground:
                    id: content_container
                    image_source: './res/a86.9.png'
                    border: 10, 18, 36, 8
                    anchor: 'right'
        Division:
            absolute_width: dp(68)
            ImageContent:
                size_hint: 0.75, None
                source: root.user_pic
    Division:
        absolute_height: dp(12)

<ChatTimeLabel>
    ShapeBackground:
        radius: 5
        color: 0.6,0.6,0.6,0.7
        LabelContent:
            margin: 16,16,8,8
            text: root.chat_time
            color: 0.2,0.2,0.2,1

<CustomTextInput>
    background_normal: './res/input.png'
    background_disabled_normal: ''
    background_active: './res/input.png'
    background_disabled_active: ''
    multiline: False

<WeixinInput>:
    canvas.before:
        Color:
            rgb: 1,1,1
        Rectangle:
            pos: 0,0
            size: self.size
        Color:
            rgb: 0.75,0.75,0.75
        Rectangle:
            pos: 0,0
            size: self.width,1
    contents_typesetting: 'anchor'
    ImageContent:
        source: './res/voice.png'
        size_hint: None, 0.65
        margin: 10,5,0,0
        anchor: 'left'
    WidgetContainer:
        WidgetLayout:
            size_hint: 0.65, 0.75
            margin: 5,5,0,0
            anchor: 'left'
        CustomTextInput:
    ImageContent:
        clear_color_state: True
        source: './res/add.png'
        size_hint: None, 0.65
        margin: 5,10,0,0
        anchor: 'right'
    ImageContent:
        source: './res/smiling.png'
        size_hint: None, 0.65
        margin: 5,5,0,0
        anchor: 'right'
''')

_s_right_image_margin = (8,16,15,15)
_s_left_image_margin = (16,8,15,15)
_s_left_text_margin = (16,8,15,25)
_s_right_text_margin = (8,16,15,25)
#225,225,225
class ChatLeftPad(RelativeComposite, StaggeredViewMixin):
    user_pic = StringProperty('')
    user_name = StringProperty('')
    def __init__(self,**kwargs):
        self.content = ''
        super(ChatLeftPad, self).__init__(**kwargs)
    def refresh_view_attrs(self, rv, data):
        self._changed_flag = True
        self.user_pic = data['user_pic']
        self.user_name =data['user_name']
        if self.content != data['content']:
            self.content = data['content']
            container = self.ids['content_container']
            self._add_content(container, data['type'], self.content)
        return

    def _add_content(self, container, type, content):
        container.clear_widgets()
        if type == 'image':
            image = ImageContent()
            image.margin = _s_left_image_margin
            image.source = content
            #image.image_size = dp(120), None
            image.max_width = dp(220)
            image.min_width = dp(80)
            container.add_widget(image)
        elif type == 'text':
            label = LabelContent()
            label.margin = _s_left_text_margin
            label.line_height = 1.3
            label.color = 0.2,0.2,0.2,1
            label.font_size = sp(15)
            label.max_width = dp(220)
            label.text = content
            container.add_widget(label)

    def compute_height(self, recycleview, index, view_width):
        self.layout(0, ref_size=(view_width, None))
        return self.height

class ChatRightPad(RelativeComposite, StaggeredViewMixin):
    user_pic = StringProperty('./res/tabimage5.png')
    def __init__(self,**kwargs):
        self.content = ''
        super(ChatRightPad, self).__init__(**kwargs)

    def refresh_view_attrs(self, rv, data):
        self._changed_flag = True
        if self.content != data['content']:
            self.content = data['content']
            container = self.ids['content_container']
            self._add_content(container, data['type'], self.content)
        return

    def _add_content(self, container, type, content):
        container.clear_widgets()
        if type == 'image':
            image = ImageContent()
            image.margin = _s_right_image_margin
            image.source = content
            #image.image_size = dp(120), None
            image.max_width = dp(220)
            image.min_width = dp(80)
            container.add_widget(image)
        elif type == 'text':
            label = LabelContent()
            label.margin = _s_right_text_margin
            label.line_height = 1.3
            label.color = 0.2,0.2,0.2,1
            label.font_size = sp(15)
            label.max_width = dp(220)
            label.text = content
            container.add_widget(label)

    def compute_height(self, recycleview, index, view_width):
        self.layout(0,ref_size=(view_width, None))
        return self.height

class ChatTimeLabel(RelativeComposite, StaggeredViewMixin):
    chat_time = StringProperty('')
    def __init__(self,**kwargs):
        super(ChatTimeLabel,self).__init__(**kwargs)
        self.size_hint_y = None
        self.height = dp(68)

    def refresh_view_attrs(self, rv, data):
        self.chat_time = data['chat_time']

class CustomTextInput(TextInput):
    def __init__(self,**kwargs):
        super(CustomTextInput,self).__init__(**kwargs)
        self.font_name = os.environ['KIVY_VALID_FONT']

class WeixinInput(RelativeComposite):
    pass


_s_user_info = [('./res/tabimage3.png','组合控件'), ('./res/tabimage2.png','交错布局控件')]

_s_chat_pic = ['./res/music-player1.png', './res/price-img-1.jpg',\
               './res/price-img-2.jpg', './res/smiling.png', './res/flower.jpg']


def generate_chat():
    data = []
    for i in range(30):
        user = randint(0,1)
        char_time = '6月{}日'.format(i + 3)
        data.append({'viewclass':'ChatTimeLabel', 'chat_time': char_time})
        data.append({'viewclass':'ChatRightPad', 'type': 'text', 'content':'你好!'})
        data.append({'viewclass':'ChatLeftPad', 'user_pic':_s_user_info[user][0], 'user_name':_s_user_info[user][1], 'type':'text','content':'你是谁？我不认识你。'})
        data.append({'viewclass':'ChatLeftPad', 'user_pic':_s_user_info[user][0], 'user_name':_s_user_info[user][1],'type':'image','content':_s_chat_pic[0]})
        data.append({'viewclass':'ChatRightPad', 'type': 'text', 'content':'我是你的好朋友，我们在一起探讨过麻将啊！'})
        data.append({'viewclass':'ChatLeftPad', 'user_pic':_s_user_info[user][0], 'user_name':_s_user_info[user][1], 'type': 'text', 'content':'啊，知道了，你是甘肃省常熟市梅营县庆佳宕婵集团公司的吧？'})
        data.append({'viewclass':'ChatRightPad', 'type': 'text', 'content':'是我啊，我都找了你三天了，你知道“世上方一日，网上已千年”，我们三千年没有见面，你仍然记得我，真是缘分哪！'})
        data.append({'viewclass':'ChatLeftPad', 'user_pic':_s_user_info[user][0], 'user_name':_s_user_info[user][1],'type': 'text', 'content':'咦，你不是叫“报废发动机”吗？'})
        data.append({'viewclass':'ChatLeftPad', 'user_pic':_s_user_info[user][0], 'user_name':_s_user_info[user][1], 'type': 'image', 'content':_s_chat_pic[3]})
        data.append({'viewclass':'ChatRightPad', 'type':'text','content':'可不是吗！我们经理批评我天天上网，精神萎靡，工作没有力度，思考缺乏深度，名副其实的“报废发动机”。我一气之下，就改了“小松挖掘机”这个名字。'})
        data.append({'viewclass':'ChatRightPad', 'type': 'image', 'content':_s_chat_pic[randint(0,4)]})
        data.append({'viewclass':'ChatRightPad', 'type': 'image', 'content':_s_chat_pic[randint(0,4)]})

    return data


